package servlet;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import dal.*;
import model.User;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	public LoginServlet() {
		super();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User user = new User(request.getParameter("username"), request
				.getParameter("password"));

		if (validate(user)) {
			HttpSession session = request.getSession(true);
			session.setAttribute("user", user);
			ServletContext application = this.getServletContext();
			HashMap<String, User> users = (HashMap<String, User>) application
					.getAttribute("users");
			if (users == null)
				users = new HashMap<String, User>();
			users.put(user.getUsername(), user);
			application.setAttribute("users", users);
			if (user.getUsername().equals("admin")) {
				session.setAttribute("manager", "");
			}else{
				session.removeAttribute("manager");
			}
			response.sendRedirect("chatroom.jsp");
			return;

		} else {
			response.sendRedirect("login_error.html");
			return;
		}
	}

	protected boolean validate(User user) {
		UserService us = new DefaultUserService();
		User vuser = us.getUser(user.getUsername());
		if (vuser != null && vuser.getPassword().equals(user.getPassword())) {
			return true;
		} else
			return false;
	}

}
